package kyssion.leetcode.num51_100;

import java.util.Deque;
import java.util.LinkedList;

public class code71_简化路径 {
    public static void main(String[] args) {
        System.out.println(new code71_简化路径().simplifyPath(
                "/a/./b/../../c/"
        ));
    }

    public String simplifyPath(String path) {
        if (!path.endsWith("/")) {
            path += "/";
        }
        char[] arr = path.toCharArray();
        Deque<StringBuffer> stack = new LinkedList<>();
        int start = 0, end = 0;
        for (int a = 0; a < arr.length; a++) {
            if (arr[a] == '/') {
                String item = path.substring(start, end);
                if (item.equals("..") && stack.size() > 0) {
                    stack.removeLast();
                } else if (!item.equals("") && !item.equals(".") && !item.equals("..")) {
                    StringBuffer iii = new StringBuffer(item);
                    stack.addLast(iii);
                }
                start = a + 1;
                end = start;
                continue;
            }
            end++;
        }
        StringBuffer ret = new StringBuffer();
        while (stack.size() > 0) {
            StringBuffer item = stack.getFirst();
            ret.append("/").append(item);
            stack.removeFirst();
        }
        String i = ret.toString();
        return i.equals("") ? "/" : i;
    }

    /**
     * 思路是一样的但是这个逼玩意为啥跑的比我快
     * @param path
     * @return
     */
    public String simplifyPath2(String path) {
        LinkedList<String> stack = new LinkedList<String>();
        int start = 0;
        int end = 0;
        while (start < path.length()) {
            while (start < path.length() && '/' == path.charAt(start)) start++;
            while (end < path.length() && '/' != path.charAt(end)) end++;
            if (start >= path.length()) break;
            String str = path.substring(start, end);
            if (str.equals(".")) {
                // do nothing
            } else if (str.equals("..")) {
                if (!stack.isEmpty()) stack.pop();
            } else {
                stack.push(str);
            }
            start = end + 1;
        }
        if (stack.isEmpty()) return "/";
        StringBuilder builder = new StringBuilder();
        while (!stack.isEmpty()) {
            builder.append('/');
            builder.append(stack.pollLast());
        }
        return builder.toString();
    }
}
